<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage } from 'element-plus'
import { getAppDetailApi, updateAppApi } from '@/api/application'
import { Application } from '@/api/application/types'

const { t } = useI18n()

const props = defineProps<{
  id: string
}>()

const editForm = reactive({
  feilds: {
    appName: '',
    appSecret: '',
    applyWay: '',
    state: '',
    contactWay: '',
    profile: ''
  }
})

const rules = reactive({
  appSecret: [
    { required: true, message: '应用密码为必填项', trigger: 'blur' },
    { min: 6, max: 20, message: '应用密码的长度应介于6到20', trigger: 'blur' }
  ]
})

const init = async () => {
  ElMessage.success(props.id)
  const res = await getAppDetailApi(props.id)
  console.log(res)
  editForm.feilds = res.data.detail
}
init()

const updateRef = ref()
const updateLoading = ref(false)
const handleUpdate = async () => {
  await updateRef.value?.validate(async (isValid: boolean) => {
    if (isValid) {
      updateLoading.value = true
      const res = await updateAppApi(editForm.feilds as Application)
        .catch(() => {})
        .finally(() => {
          updateLoading.value = false
        })
      if (res) {
        ElMessage.warning(res.msg)
      }
    }
  })
}
</script>

<template>
  <ElForm ref="updateRef" :model="editForm" :rules="rules">
    <ElFormItem :label="t('application.appName')">
      <ElInput v-model="editForm.feilds.appName" disabled />
    </ElFormItem>
    <ElFormItem :label="t('application.appSecret')">
      <ElInput v-model="editForm.feilds.appSecret" />
    </ElFormItem>
    <ElFormItem :label="t('application.contactWay')">
      <ElInput v-model="editForm.feilds.contactWay" />
    </ElFormItem>
    <ElFormItem :label="t('application.profile')">
      <ElInput
        v-model="editForm.feilds.profile"
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 5 }"
      />
    </ElFormItem>
    <ElRow :gutter="5">
      <ElCol :span="12">
        <ElFormItem :label="t('application.applyWay')">
          <ElSelect v-model="editForm.feilds.applyWay">
            <ElOption value="free" label="无需申请" />
            <ElOption value="self" label="自助申请" />
            <ElOption value="invite" label="管理员邀请" />
          </ElSelect>
        </ElFormItem>
      </ElCol>
      <ElCol :span="12">
        <ElFormItem :label="t('application.state')">
          <ElSelect v-model="editForm.feilds.state">
            <ElOption value="developing" :label="t('application.developing')" />
            <ElOption value="online" :label="t('application.online')" />
            <ElOption value="offline" :label="t('application.offline')" />
          </ElSelect>
        </ElFormItem>
      </ElCol>
    </ElRow>
    <ElFormItem>
      <ElButton type="primary" @click="handleUpdate" :loading="updateLoading">
        {{ t('common.submit') }}
      </ElButton>
    </ElFormItem>
  </ElForm>
</template>
